package com.uniledger.exchange;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.uniledger.exchange.model.OkSingleton;

import org.stellar.sdk.AssetTypeCreditAlphaNum4;
import org.stellar.sdk.AssetTypeNative;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Memo;
import org.stellar.sdk.Network;
import org.stellar.sdk.PaymentOperation;
import org.stellar.sdk.Server;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.SubmitTransactionResponse;

import java.io.IOException;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;

public class StellarActivity extends AppCompatActivity {

    public static final String TAG = "Stellar";

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, StellarActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stellar);
        new StellarTask().execute();
    }

    static class StellarTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... strings) {

            Network.useTestNetwork();
            Server server = new Server("https://horizon-testnet.stellar.org");
            KeyPair source = KeyPair.fromSecretSeed("SATZMC5FHZDQKS5VSJZGZZM3JU2M2TWBG4NNAIX2DWLX73VE4JDUT442");
            KeyPair destination = KeyPair.fromAccountId("GBNWEOA4GPIKUOBAKAOTR6V3DNRMCXMGCBSXI5LMSDE2TT3GP4B2QHJC");
            try {
                server.accounts().account(destination);
                AccountResponse sourceAccount = server.accounts().account(source);
                Transaction transaction = new Transaction.Builder(sourceAccount)
                        .addOperation(new PaymentOperation.Builder(destination, new AssetTypeNative(), "10").build())
                        .addMemo(Memo.text("Test Transaction"))
                        .build();
                transaction.sign(source);
                SubmitTransactionResponse response = server.submitTransaction(transaction);
                Log.d(TAG, "Success!");
                Log.d(TAG, response.getResultXdr());
            } catch (IOException e) {
                Log.d(TAG, "Something went wrong!");
                Log.d(TAG, e.getMessage());
            }

            return null;
        }
    }
}
